﻿package at.geoathome.utils.loader
{
	
	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.media.Sound;
	import flash.net.URLRequest; 

	/**
	* ...
	* @author Georg Kamptner
	*/
	public class SoundLoader 
	{
		private var _req:URLRequest;
		private var _sound:Sound; //internal sound
		private var _connected:Boolean; //state of sound
		
		public function SoundLoader(url:URLRequest=null) 
		{
			_req = new URLRequest(url);
			_connected = false;
		}

		/**
		 * Returns the status of sound
		 * @return true if connected else false
		 */
		public function get connected():Boolean
		{
			return _connected;
		}
		/**
		 * Get the duration
		 * @return duration
		 */
		public function get duration():Number
		{
			return int(sound.length/(sound.bytesLoaded/sound.bytesTotal));
		}

		public function getResult():Sound
		{
			return _sound;
		}

		/**
		 * loads a sound from the specified url. if you specified it already in the constructor you can omit it.
		 */
		public function load(request:URLRequest=null):void
		{
			if(request != null)
				_req = request;
		   
			//if there is one running, close it
			if (_sound)
				if (_sound.isBuffering)
					_sound.close();
		   
			//create a new sound to avoid Error: 2037 <-- anyone knows why this error happens?
			_sound = new Sound();
			_sound.addEventListener(ProgressEvent.PROGRESS, delegate);
			_sound.addEventListener(Event.OPEN, delegate);
			_sound.load(_req);
		   
			//set connected to true
			_connected = true;
		}
		
		/**
		 * Stops the loading of a sound
		 */
		public override function stop():void
		{
			_sound.close();
			_connected = false;
		}

		/**
		 * simply delegates the event
		 */
		private function delegate( event:Event ):void
		{
			dispatchEvent(event);
		}
		
	}
	
}